package cn.ljy.authority.config;

import cn.ljy.authority.web.interceptor.LoginForAdminOfFrontendInterceptor;
import cn.ljy.authority.web.resolver.LoginUserTokenAugumentResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.LinkedList;
import java.util.List;

/**
 * 拦截器配置
 */
@Configuration
public class SysWebConfigurer implements WebMvcConfigurer {

//    @Override
//    public void addResourceHandlers(ResourceHandlerRegistry registry) {
//        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
//    }

    @Autowired
    private LoginUserTokenAugumentResolver loginUserTokenAugumentResolver;

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        //增加当前登录用户的token信息的处理
        resolvers.add(loginUserTokenAugumentResolver);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //账户登录验证的拦截器
        registry.addInterceptor(loginForAdminOfFrontendInterceptor())
                .addPathPatterns("/api/websocket/oauth/**")//要拦截的路径
                .addPathPatterns("/api/frontend/user/**")//要拦截的路径
                .addPathPatterns("/api/frontend/pc/user/**")//要拦截的路径
                .addPathPatterns("/api/frontend/mobile/user/**")//要拦截的路径
                .excludePathPatterns(new LinkedList<String>() {{//不拦截的路径（一般指addPathPatterns中包含，但是不进行拦截的特例）
                    add("/api/frontend/logout");
                }});
    }

    //创建拦截器对象，只有通过这里才能让拦截器中的依赖注入生效
    //前台拦截器账户登录验证
    @Bean
    public LoginForAdminOfFrontendInterceptor loginForAdminOfFrontendInterceptor() {
        return new LoginForAdminOfFrontendInterceptor();
    }

    /**
     * 20240719增加
     * 为接口请求添加一个统一的前缀
     * @param configurer
     */
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
//        configurer.addPathPrefix("/api",c->c.getPackage().getName().contains("cn.ljy.authority.web.controller"));
        configurer.addPathPrefix("/api", c ->
                c.getPackage().getName().contains("cn.ljy.authority.web.controller") ||
                        c.getPackage().getName().contains("cn.ljy.mes.web.controller"));
    }
}
